package com.rc.evcharger.task;

import com.github.pagehelper.util.StringUtil;
import com.rc.evcharger.biz.notify.NotifyStopChargeResult;
import com.rc.evcharger.common.base.BaseTask;
import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.common.utils.DataUtil;
import com.rc.evcharger.common.utils.TimeoutUtil;
import com.rc.evcharger.model.elec.ElecGun;
import com.rc.evcharger.model.elec.ElecPile;
import com.rc.evcharger.model.order.OrderInfo;
import com.rc.evcharger.redis.RedChargeDataService;
import com.rc.evcharger.redis.RedOrderService;
import com.rc.evcharger.redis.RedisService;
import com.rc.evcharger.service.OrderCostService;
import com.rc.evcharger.service.elec.ElecGunService;
import com.rc.evcharger.service.elec.ElecPileService;
import com.rc.evcharger.service.order.OrderInfoService;
import io.netty.util.Timeout;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 异常订单结算定时器
 *
 * @author Administrator
 */
@Component
public class ExOrderTask extends SupperTask implements BaseTask {
    private static Logger logger = LogManager.getLogger(ExOrderTask.class);

    @Autowired
    private RedisService redisService;

    @Autowired
    private RedOrderService redOrderService;

    @Autowired
    private OrderCostService orderCostService;

    @Autowired
    private NotifyStopChargeResult notifyStopChargeResult;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private RedChargeDataService redChargeDataService;


    @Override
    public void runTask(Timeout timeout) {
        TimeoutUtil timeoutUtil = TimeoutUtil.newInstance();
        String key = timeoutUtil.getRtua(timeout);

        timeout.cancel();
        timeoutUtil.removeTimeout(key);
        logger.warn("exOrderTask: 执行的key为：" + key);
        if (key == null) {
            return;
        }
        key = key.replace(this.getClass().getName(), "");

        int index = key.lastIndexOf(" ");
        String orderNum = key.substring(index + 1);

        if (StringUtils.isEmpty(orderNum)) {
            return;
        }

        OrderInfo orderInfo = orderInfoService.selectByOrderNum(orderNum);
        if (orderInfo == null) {
            return;
        }

        logger.warn("订单异常结算：对应KEY:{}", key);

        //扫描结算
        orderCostService.updateOrderCost(orderInfo.getOrderNum(), SocketConstant.STOP_ELELPILE_INTERNET_EXCEPTION_0x3);

        //推送订单停止状态
        notifyStopChargeResult.notifyOrderStop(orderInfo.getOrderNum(), SocketConstant.CON0, SocketConstant.CON1, 0);

    }

    @Override
    public void removeTask(String rtua) {
        TimeoutUtil timeoutUtil = TimeoutUtil.newInstance();

        ElecPile pile = elecPileService.selectPileByLogicAddress(rtua);
        List<ElecGun> elecGuns = elecGunService.listByElecPileId(pile.getElecPileId());

        for (ElecGun elecGun : elecGuns) {
            OrderInfo orderInfo = orderInfoService.selectByPileIdAndGunId(pile.getElecPileId(), elecGun.getElecGunId());
            if (orderInfo == null){
                continue;
            }
            //是否在充电中的订单号
            String orderNum = redChargeDataService.getOrderNum(rtua, elecGun.getGunNum(), orderInfo.getOrderNum());
            if (StringUtil.isEmpty(orderNum)){
                return;
            }

            //构建key
            String key = this.getClass().getName() + DataUtil.getKey(rtua, elecGun.getGunNum(), orderInfo.getOrderNum());
            Timeout timeout = timeoutUtil.getTimeout(key);
            logger.warn("订单结算定时器移除桩地址" + key);
            if (timeout != null) {
                timeout.cancel();
                timeoutUtil.removeTimeout(key);
            }
        }
    }

    @Override
    public void addTask(String rtua, String gunNum, Integer time, TimeUnit tu) {
        TimeUnit timeUnit = TimeUnit.SECONDS;
        if (tu != null) {
            timeUnit = tu;
        }
        if (time == null) {
            time = this.SECONDS;
        }

        ElecPile pile = elecPileService.selectPileByLogicAddress(rtua);
        List<ElecGun> elecGuns = elecGunService.listByElecPileId(pile.getElecPileId());

        for (ElecGun elecGun : elecGuns) {

            OrderInfo orderInfo = orderInfoService.selectByPileIdAndGunId(pile.getElecPileId(), elecGun.getElecGunId());
            if (orderInfo == null || "2".equals(orderInfo.getStatus())) {
                continue;
            }
            //从redis里根据
            logger.warn("订单结算定时器添加桩地址" + rtua);

            TimeoutUtil timeoutUtil = TimeoutUtil.newInstance();
            Timeout timeout = timer.newTimeout(this, time, timeUnit);

            //构建key
            String key = this.getClass().getName() + DataUtil.getKey(rtua, elecGun.getGunNum(), orderInfo.getOrderNum());
            logger.warn("订单结算定时器key" + this.getClass().getName() + key);

            timeoutUtil.addTimeout(key, timeout);
        }
    }


    //@Override
    //public void runTask(Timeout timeout) throws Exception {
    //    TimeoutUtil timeoutUtil = TimeoutUtil.newInstance();
    //    String key = timeoutUtil.getRtua(timeout);
    //    logger.warn("exOrderTask: 执行的key为：" + key);
    //    if (key == null) {
    //        return;
    //    }
    //    String rtua = key.replace(this.getClass().getName(), "");
    //    logger.warn("exOrderTask: 执行的rtua为：" + rtua);
    //    if (rtua == null) {
    //        logger.warn("订单异常结算有一个定时器异常");
    //        return;
    //    }
    //    List<RedOrder> list = (List<RedOrder>) redisService.getObjects(new RedOrder(rtua));
    //    if (CollectionUtils.isEmpty(list)) {
    //        return;
    //    }
    //    for (RedOrder order : list) {
    //        try {
    //            logger.warn("订单异常结算：桩地址:" + rtua + "订单id:" + order.getKey());
    //
    //            //扫描结算
    //            orderCostService.updateOrderCost(order.getOrderNum(), SocketConstant.STOP_ELELPILE_INTERNET_EXCEPTION_0x3);
    //
    //            //推送订单停止状态
    //            notifyStopChargeResult.notifyOrderStop(order.getOrderNum(), SocketConstant.CON0, SocketConstant.CON1, 0);
    //
    //        } catch (Exception e) {
    //            logger.error("订单异常结算出错", e);
    //        }
    //    }
    //    timeout.cancel();
    //    timeoutUtil.removeTimeout(rtua);
    //}
    //
    //@Override
    //public void removeTask(String rtua) {
    //    TimeoutUtil timeoutUtil = TimeoutUtil.newInstance();
    //    Timeout timeout = timeoutUtil.getTimeout(this.getClass().getName() + rtua);
    //    logger.warn("订单结算定时器移除桩地址" + this.getClass().getName() + rtua);
    //    if (timeout != null) {
    //        timeout.cancel();
    //        timeoutUtil.removeTimeout(this.getClass().getName() + rtua);
    //    }
    //}
    //
    //@Override
    //public void addTask(String rtua, String gunNum, Integer time, TimeUnit tu) {
    //    TimeUnit timeUnit = TimeUnit.SECONDS;
    //    if (tu != null) {
    //        timeUnit = tu;
    //    }
    //    if (time == null) {
    //        time = this.SECONDS;
    //    }
    //    //从redis里根据
    //    if (redOrderService.hasOrder(rtua, gunNum, null)) {
    //        logger.warn("订单结算定时器添加桩地址" + rtua);
    //
    //        TimeoutUtil timeoutUtil = TimeoutUtil.newInstance();
    //        Timeout timeout = timer.newTimeout(this, time, timeUnit);
    //
    //        String key = DataUtil.getKey(rtua, gunNum);
    //        logger.warn("订单结算定时器key" + this.getClass().getName() + key);
    //
    //        timeoutUtil.addTimeout(this.getClass().getName() + key, timeout);
    //    }
    //}

}
